package org.grow.erp.entity;

import lombok.Data;
import org.grow.erp.service.PriceReducedBill;
import org.hibernate.annotations.GenericGenerator;

import javax.persistence.*;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: xwg
 * @CreateDate: 2022/1/19
 */

@Data
@Entity
public class OutStockBill implements PriceReducedBill {
    /*    单据编号	单据日期	仓库	领用部门	领用人 	备注
        金额合计	制单人	制单状态	审核人	审核状态*/
    /**后端确定字段 4 */
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO, generator = "hi")
    @GenericGenerator(name = "hi", strategy = "assigned")
    private String outStockCode;

    //    金额合计 计算属性
    private BigDecimal totalAmount;
//    表逻辑删除乐观锁 相关
    private Boolean abandoned = false;
    @Version
    private Integer version = 0;

   /** 前端信任字段 5 */
    //    库位
    private String storeHouse;
    //    领用部门
    @Enumerated(EnumType.STRING)
    private Department applyDepartment = Department.sale;
    //    领用人
    private String applier;
    //    备注
    private String comment;
    //    出库领用时间
    private LocalDateTime outStockTime;

/** 流程状态相关 4 */
    //制单人 制单状态
    private String billOperator;
    @Enumerated(EnumType.STRING)
    private OperateState operateState = OperateState.notSubmit;
    //审核人	审核结果
    private String billAuditor;
    @Enumerated(EnumType.STRING)
    private AuditState auditState = AuditState.NA;


    @OneToMany(cascade = CascadeType.ALL, mappedBy = "outStockBill",orphanRemoval = true )
    private List<OutStockMaterialDetail> outStockMaterialDetails = new ArrayList<>(5);


    @Override
    public void refreshComputedFields() {
        BigDecimal total = new BigDecimal(0);
        for (OutStockMaterialDetail detail : outStockMaterialDetails) {
            detail.setAmount(detail.getUnitPrice().multiply(new BigDecimal(detail.getQuantity())));
            total = total.add(detail.getAmount());
        }
        this.setTotalAmount(total);
    }

    @Override
    public void refreshDomainRelationship() {
        this.outStockMaterialDetails.forEach(x -> {
            x.getOutStockMaterialDetailId().setOutStockFk(this.getOutStockCode());
            x.setOutStockBill(this);
        });
    }
}
